//
//  HomeSearchVC.m
//  Tour
//
//  Created by hesiyao on 16/3/10.
//  Copyright © 2016年 张中烨. All rights reserved.
//

#import "HomeSearchVC.h"

#import <QuartzCore/QuartzCore.h>
#import "Definition.h"


#import "PrefixHeader.pch"

#import <iflyMSC/IFlyDataUploader.h>
#import<iflyMSC/IFlySpeechConstant.h>
@class PopupView;
@class IFlyDataUploader;
@class IFlySpeechRecognizer;

@interface HomeSearchVC ()<UISearchBarDelegate, UITableViewDelegate,UITableViewDataSource,IFlyRecognizerViewDelegate,IFlySpeechRecognizerDelegate,UIActionSheetDelegate>

@property (nonatomic, strong) NSString *pcmFilePath;//音频文件路径
@property (nonatomic, strong) IFlySpeechRecognizer *iFlySpeechRecognizer;//不带界面的识别对象
@property (nonatomic, strong) IFlyRecognizerView *iflyRecognizerView;//带界面的识别对象
@property (nonatomic, strong) IFlyDataUploader *uploader;//数据上传对象
@property (nonatomic, strong) PopupView *popUpView;
@property (nonatomic, strong) NSString * result;
@property (nonatomic, assign) BOOL isCanceled;


@property (strong, nonatomic) UITextView *textView;

@property (nonatomic, retain) UISearchController *search;/**< 搜索控制视图 */
@property (nonatomic, copy) NSString *strHight;/**< 高亮用字符串 保存搜索信息 */
@property (nonatomic, retain) NSMutableArray *dataArr;/**< 接收数据数组 */
@property (nonatomic, retain) BaseTableView *tableView;/**< 显示数据内容 */
@end

@implementation HomeSearchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    //初始化视图
    [self createSubviews];
    


    
}

//初始化视图
- (void)createSubviews
{
    //返回按钮
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"back" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    

    //右按钮 语音识别
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"语音"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(yuYinShiBie)];
    
    // 初始化搜索视图
    self.search = [[UISearchController alloc]initWithSearchResultsController:nil];
    // 签订协议
    //    _search.searchResultsUpdater = self;
    _search.searchBar.delegate = self;
    // 屏幕变灰 yes时tableview 不能下拉
    _search.dimsBackgroundDuringPresentation = NO;
    // 设置点击搜索框时 隐藏导航栏
    _search.hidesNavigationBarDuringPresentation = NO;
    // 占位符 默认search
    _search.searchBar.placeholder = @"请输入搜索内容";
    
    // 搜索栏的风格
    _search.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    // 把 搜索视图加到导航栏上
    self.navigationItem.titleView = _search.searchBar;
    // 自适应
    [_search.searchBar sizeToFit];
    
    self.tableView = [[BaseTableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    //数据上传对象初始化
    self.uploader = [[IFlyDataUploader alloc] init];
    
    //demo录音文件保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    _pcmFilePath = [[NSString alloc] initWithFormat:@"%@",[cachePath stringByAppendingPathComponent:@"asr.pcm"]];
    
//    [self initRecognizer];//初始化识别对象
    

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc
{
    
}

//语音识别方法
- (void)yuYinShiBie
          
{
    if ([IATConfig sharedInstance].haveView == NO) {//无界面
        if(_iflyRecognizerView == nil)
        {
            [self initRecognizer ];
        }
        
        [self.search.searchBar setText:@""];
        [self.search.searchBar resignFirstResponder];
        
        //设置音频来源为麦克风
        [_iflyRecognizerView setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //设置听写结果格式为json
        [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //保存录音文件，保存在sdk工作路径中，如未设置工作路径，则默认保存在library/cache下
        [_iflyRecognizerView setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        [_iflyRecognizerView start];
    }

    
}
- (void) onCancel
{
    NSLog(@"%s",__func__);
}
-(void)initRecognizer
{
    //单例模式，UI的实例
    if (_iflyRecognizerView == nil) {
        //UI显示剧中
        _iflyRecognizerView= [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
        
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        //设置听写模式
        [_iflyRecognizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        
    }
    _iflyRecognizerView.delegate = self;
    
    if (_iflyRecognizerView != nil) {
        IATConfig *instance = [IATConfig sharedInstance];
        //设置最长录音时间
        [_iflyRecognizerView setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
        //设置后端点
        [_iflyRecognizerView setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
        //设置前端点
        [_iflyRecognizerView setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
        //设置采样率，推荐使用16K
        [_iflyRecognizerView setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
        if ([instance.language isEqualToString:[IATConfig chinese]]) {
            //设置语言
            [_iflyRecognizerView setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //设置方言
            [_iflyRecognizerView setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
        }else if ([instance.language isEqualToString:[IATConfig english]]) {
            //设置语言
            [_iflyRecognizerView setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
        }
        //设置是否返回标点符号
        [_iflyRecognizerView setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
        
        //        }
    }

}


- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast
{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    self.search.searchBar.text = [NSString stringWithFormat:@"%@%@",self.search.searchBar.text,result];
}

//搜索方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.strHight = [self.search.searchBar text];
    NSLog(@"%@", _strHight);
    if ([_strHight containsString:@" "]) {
        // 盘算如果有空格不执行
        // 没有则执行一下程序
        // 不写这个判断 打空格就会崩溃
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"没有您要搜索的内容" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }else
    {
        [MBProgressHUDManager showHUDtoView:self.view string:@"正在加载中..."];
        // 中文转码
        NSString *urlStr = [_strHight stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:_strHight]];
        
        // 变化的参数进行拼接
        NSString *str = [@"http://open.qyer.com/qyer/search/index?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&keyword=%E9%A6%99%E6%B8%AF&oauth_token=89dd34fbffaaa72503b4baa7a9d02812&page=1&place_field=country%7Ccity%7Cpoi&track_app_channel=App%2520Store&track_app_version=6.8.3&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=CDA3EEEB-61BF-473E-AFFF-32B6332C9BBF&track_os=ios%25207.1.2&track_user_id=7328550&type=place&v=1" stringByReplacingOccurrencesOfString:@"keyword=%E9%A6%99%E6%B8%AF" withString:[NSString stringWithFormat:@"keyword=%@", urlStr]];
        NSLog(@"%@", str);
//        [AFNModel GETWithHandler:str completion:^(id result) {
//            self.dataArr = [HomeSearchModel modelHanderWithArray:result[@"data"][@"entry"]];
////            NSMutableArray *arr =result[@"data"][@"entry"];
//            NSLog(@"%@", result);
//            [_tableView reloadData];
//            
//            if (_dataArr.count == 0) {
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"没有您要搜索的内容" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//                [alert show];
//                
//            }
//        }];
        
        AFHTTPSessionManager *sessionManage = [AFHTTPSessionManager manager];
        [sessionManage GET:str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            self.dataArr = [HomeSearchModel modelHanderWithArray:responseObject[@"data"][@"entry"]];
            NSLog(@"%@", responseObject);
            [_tableView reloadData];
            
            if (_dataArr.count == 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"没有您要搜索的内容" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alert show];
                
            }
            [MBProgressHUDManager removeHUD];

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}

#pragma mark -  判断emoji表情
-(BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
             
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    
    return returnValue;
}
#pragma mark - 判断非法字符
- (BOOL)isHaveIllegalChar:(NSString *)str{
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"[]{}?!@（#%-*+=）/\\|~(＜＞$%^*)_+ "];
    NSRange range = [str rangeOfCharacterFromSet:doNotWant];
    return range.location<str.length;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    HomeSearchModel *model = _dataArr[indexPath.row];
    NSMutableAttributedString *keyword = [[NSMutableAttributedString alloc]initWithString:model.cnname];
    NSRange range = [model.cnname rangeOfString:_strHight];
    [keyword setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName: [UIFont systemFontOfSize:20]} range:range];
    cell.textLabel.attributedText = keyword;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消tableview 选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HomeSearchModel *model = _dataArr[indexPath.row];
    if ([model.label isEqualToString:@"美食"]){
        HomeSearchFoodVC *searchFoodVC = [HomeSearchFoodVC alloc];
        searchFoodVC.cellid = model.key;
        [self.navigationController pushViewController:searchFoodVC animated:YES];
    }else if ([model.label isEqualToString:@"城市"]) {
        QpCityDetailsViewController *qp = [QpCityDetailsViewController alloc];
        qp.cityid = model.key;
        [self.navigationController pushViewController:qp animated:YES];
    }

    
}
///返回按钮方法
-(void)back
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
